import router from '@/router'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import pinia from './store'
import useUserStore from '@/store/modules/user'
import setting from './setting'

nprogress.configure({ showSpinner: false })

const userStore = useUserStore(pinia)

router.beforeEach(async (to, from, next) => {
  document.title = `${setting.title} - ${to.meta.title}`
  nprogress.start()
  const token = userStore.token
  if (token) {
    to.path === '/login'
      ? next('/')
      : userStore.userName
        ? next()
        : await userStore
            .userInfo()
            .then(() => {
              next()
            })
            .catch(async (err) => {
              await userStore.logout()
              next({ path: '/login', query: { redirect: to.path } })
            })
  } else {
    to.path === '/login'
      ? next()
      : next({ path: '/login', query: { redirect: to.path } })
  }
})

router.afterEach((to, from) => {
  nprogress.done()
})
